import { Component, OnInit } from '@angular/core';
import { RandomUserService } from '../../../../home/randomUser.service';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import { getFakeChartData } from '../../../../../../../_mock/chart.service';
import { _HttpClient } from '@core/services/http.client';
import { HttpClient, HttpParams } from '@angular/common/http';
import { getRule, saveRule, removeRule } from '../../../../../../../_mock/rule.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpService } from '@core/services/http.service';
import { ActivatedRoute, Router } from '@angular/router';
import { FileUploader } from 'ng2-file-upload';
import { DomSanitizer } from '@angular/platform-browser';
import swal, { SweetAlertType } from 'sweetalert2';
declare var jsPlumb: any;
const URL = 'https://139.196.189.173:8089/VisualizationMgt/fileUp/uploadFile';


@Component({
    selector: 'app-role',
    templateUrl: './role.component.html',
    styles: [`
        :host ::ng-deep .vertical-center-modal {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        :host ::ng-deep .vertical-center-modal .ant-modal {
            top: 100px;
        }
    `],
    styleUrls: ['./role.component.less']
})
export class RoleComponent implements OnInit {
    q: any = {
        pi: 1,
        ps: 10,
        sorter: '',
        status: -1,
        statusList: []
    };

    currNode;
    list = new Array<Node>();
    rightSrc;
    role = JSON.parse(localStorage.getItem('_user')).role;

    fileChange($event) {

        this.file = $event.target.files[0];
        // this.rightData.text = this.file.name;
    }

    onBlur() {
        for (const data of this.nids) {
            if (data.value === this.currNode.id) {
                data.label = this.currNode.text;
            }
        }
    }

    // fileChange($event) {
    //     const file: File = $event.target.files[0];
    //     const myReader: FileReader = new FileReader();
    //     const that = this;
    //     myReader.onloadend = (loadEvent: any) => {
    //         this.currNode.props.group_img = loadEvent.target.result;
    //         that.rightSrc = loadEvent.target.result;
    //         // const img = new Image();
    //
    //         // img.src = loadEvent.target.result;
    //         // img.onload = function() {
    //         //     that.rightStyleW = this['width'];
    //         //     that.rightStyleH = this['height'];
    //         // };
    //     };
    //     myReader.readAsDataURL(file);
    // }

    editNode(i, ev?, g_id?) {
        //console.log(i)
        if (ev) {
            ev.stopPropagation()
        }
        this.insertFlag = false
        this.modalVisible = true
        this.currNode = i;
        if (i.type == "group") {
            this.rightSrc = this.Http.IP_PORT + i.props.group_img
        }

        this.currNode.group_id = g_id


    }

    _checked
    data: any[] = [];
    loading = false;
    selectedRows: any[] = [];
    curRows: any[] = [];
    totalCallNo = 0;
    allChecked = false;
    indeterminate = false;
    gids = [
        { label: '默认分组', value: '-1' },

    ];
    ntypes = [
        { text: '默认', value: 'process', type: 'default' },
        { text: '逻辑分支', value: 'fork', type: 'default' },
        // {text: '开始', value: 'start', type: 'default'},
        { text: '结束', value: 'end', type: 'default' },
        { text: '空节点', value: 'empty', type: 'default' },
        // {text: '准备分组', value: 'grouping', type: 'default'}


    ];
    gtypes = [
        { text: '默认', value: 'default', type: 'default' },
        { text: '固定人数', value: 'fixed', type: 'default' },
        { text: '百分比', value: 'percent', type: 'default' },
        { text: '剩余', value: 'remain', type: 'default' }
    ];
    status = [
        { text: '关闭', value: false, type: 'default' },
        { text: '运行中', value: false, type: 'processing' },
        { text: '已上线', value: false, type: 'success' },
        { text: '异常', value: false, type: 'error' }
    ];
    sortMap: any = {};
    expandForm = false;
    modalVisible = false;
    description = '';
    insertFlag = false;

    beginData;
    addBeginAndGroup() {
        if (this.role == 3) {
            this.beginData = {
                'p_id': this.p_id,
                'processs': [
                    {
                        'group_id': '-1',
                        'id': this.getId(),
                        'node_id': [parseInt(this.getId()) + 1 + ''],
                        'nodes': [],
                        'props': {},
                        'style': {},
                        'text': '开始',
                        'type': 'start',
                        'visibleGroup': ['-1']
                    },
                    {
                        'group_id': '-1',
                        'id': parseInt(this.getId()) + 1 + '',
                        'node_id': [],
                        'nodes': [],
                        'props': {},
                        'style': {},
                        'text': '分组',
                        'type': 'grouping',
                        'visibleGroup': ['-1']
                    }
                    // , {
                    //     'group_id': '-1',
                    //     'id': parseInt(this.getId()) + 2 + '',
                    //     'node_id': [],
                    //     'nodes': [],
                    //     'props': {},
                    //     'style': {},
                    //     'text': '结束',
                    //     'type': 'end',
                    //     'visibleGroup': ['-1']
                    // }
                ],
                'isCloud': this.typename
            }
        } else {
            this.beginData = {
                'p_id': this.p_id,
                'processs': [
                    {
                        'group_id': '-1',
                        'id': this.getId(),
                        'node_id': [parseInt(this.getId()) + 1 + ''],
                        'nodes': [],
                        'props': {},
                        'style': {},
                        'text': '开始',
                        'type': 'start',
                        'visibleGroup': ['-1']
                    },
                    {
                        'group_id': '-1',
                        'id': parseInt(this.getId()) + 1 + '',
                        'node_id': [],
                        'nodes': [],
                        'props': {},
                        'style': {},
                        'text': '分组',
                        'type': 'grouping',
                        'visibleGroup': ['-1']
                    }
                    // , {
                    //     'group_id': '-1',
                    //     'id': parseInt(this.getId()) + 2 + '',
                    //     'node_id': [],
                    //     'nodes': [],
                    //     'props': {},
                    //     'style': {},
                    //     'text': '结束',
                    //     'type': 'end',
                    //     'visibleGroup': ['-1']
                    // }
                ],
                'isCloud': this.typename
            }
        }

        this.Http.saveFlow(this.beginData).subscribe(v => {
            if (v['code'] === '0') {
                // swal(`${v['msg']}`, '', 'info');
                let p;
                // if (this.role == 3) {
                p = { p_id: this.p_id, isCloud: this.typename }
                // } else {
                //     p = { p_id: this.p_id, isCloud: 'false' }
                // }
                this.Http.getProjProcess(p).subscribe(res => {

                    this.list = JSON.parse(res['list'][0]['p_data']);

                    this.updateGids();
                    this.updateNodes();
                })
            }
        });
    }


    tempgnode;
    copy(gid, ev?) {
        const g_id = gid
        //console.log(gid)
        if (ev) {
            ev.stopPropagation()
        }

    }

    addEl(gid, ev?) {
        if (ev) {
            ev.stopPropagation()
        }

        this.insertFlag = true
        this.modalVisible = true
        this.insertModel = new Node();
        this.insertModel.group_id = gid
        this.insertModel.id = this.getId();
        this.insertModel.visibleGroup.push(gid);
    }

    nodeNameChange() {
        if (!this.currNode.text.trim()) {
            this.currNode.text = ''
        }
        this.updateNodes();
    }
    groupNameChange() {
        if (!this.currNode.props.group_text.trim()) {
            this.currNode.props.group_text = ''
        }
    }
    autoAdd(l, i, j) {

        // 新增下一步节点;(需要给当前节点(通过this.list[i].nodes[j])的node_id内添加下一步节点的id);
        const node = new Node();

        node.visibleGroup = [l.id];
        node.id = this.getId();
        node.group_id = l.id;
        // 节点类型 默认为process
        node.type = 'process';
        node.text = '节点';
        // 在该（i）分组内push新节点
        this.list[i].nodes.push(node);

        // 同上上(给（i，j）节点(this.list[i].nodes[j])的node_id内添加下一步（新增节点）节点的id);
        this.list[i].nodes[j].node_id.push(node.id);

        this.list[i].nodes[j].node_id = this.list[i].nodes[j].node_id.filter((v, i) => {

            if (v === node.id) {
                return true;
            } else {
                return false;
            }

        })

        this.sortNextId(l.id);
        this.getData();

    }

    insertModel = new Node();

    filterNodeId() {

        // 更新分组节点内下一步节点数组；
        this.list[1].node_id = [];

        for (const val of this.list) {
            if (val.type !== 'end' && val.nodes.length > 0) {
                this.list[1].node_id.push(val.nodes[0].id);
            }
        }


    }

    // 在指定节点前添加节点
    addBeforeNode() {

        // console.log(this.currNode); // 当前被点击的节点
        // console.log(this.groupIndex); // 被点击节点所处分组
        // console.log(this.list);      // 大list;

        const node = new Node();
        const currGroup = this.list[this.groupIndex];
        node.visibleGroup = [currGroup.id]; // 可见组 默认当前分组
        node.id = this.getId(); // 获取分组
        node.group_id = currGroup.id; // 所处分组id;
        // 节点类型 默认为process
        node.type = 'process';
        node.text = '插入节点';

        // 寻找被点击的节点
        for (let i = 0; i < currGroup.nodes.length; i++) {
            if (currGroup.nodes[i].id === this.currNode.id) {
                currGroup.nodes.splice(i, 0, node)
                break;
            }
        }

        this.filterNodeId();
        this.sortNextId(node.group_id);
        this.updateGids();
        this.updateNodes();
        this.getData();
        this.modalVisible = false;
    }

    insert() {

        // 只有新建分组时调用insert()


        this.rightSrc = '';

        // 新增分组时在分组内创建默认的一个节点；
        const node = new Node();
        // 可见该节点的分组
        node.visibleGroup = [this.insertModel.id];
        node.node_id = [];
        // 父分组的id
        node.group_id = this.insertModel.id;
        node.text = '节点';
        // 默认节点类型 process
        node.type = 'process';
        // 该节点id
        node.id = this.getId();
        // 将新添加的！！节点！！id 添加至type为grouping的分组节点中
        this.list[1].node_id.push(node.id);

        if (this.insertModel.group_id != '-1') {
            for (let s of this.list) {
                if (s.id == this.insertModel.group_id) {
                    s.nodes.push(this.insertModel);
                }
            }
        } else {
            this.insertModel.nodes.push(node);
            this.insertList(this.insertModel, this.curIndex);
        }

        // 筛选存在的分组第一个节点，存至type 为grouping的节点的 node_id
        // this.filterNodeId();

        this.modalVisible = false;
        this.updateGids();
        this.updateNodes();
        this.getData();
    }

    sortList() {

    }

    // 暂存每阶段group下标;
    groupArr = [];
    // 序列下一步节点（除分组内最后一步节点）;
    sortFirst(node, i) {
        // 如果为第一次调用 清空首节点node_id;
        if (i === 0) {
            node.node_id = [];
        }
        // i为数组最后一个递归，跳出；
        if ((i + 1) < this.list.length) {
            // 当前node的下一个节点为group时取出其内部第一个子节点的id;
            if (this.list[i + 1].type === 'group') {

                this.groupArr.push(i + 1);

                node.node_id.push(this.list[i + 1].nodes[0].id);

                // 每次递归查询group的下一个节点（i+2）是否为group
                // 如不是，更新递归第一个参数的node节点;
                if ((i + 2) < this.list.length) {
                    if (this.list[i + 2].type !== 'group') {

                        // 将此节点的id放入其前置位的group内nodes的最后一个节点上;
                        for (let j = 0; j < this.groupArr.length; j++) {
                            const length = this.list[this.groupArr[j]].nodes.length
                            const last = length - 1;
                            if (length > 0) {
                                this.list[this.groupArr[j]].nodes[last].node_id = [this.list[i + 2].id];
                            }
                        }
                        //console.log(this.groupArr);
                        // 重置;
                        this.groupArr = [];

                        this.list[i + 2].node_id = [];
                        this.sortFirst(this.list[i + 2], i + 2);
                    } else { // 如仍是group节点 继续传递上一次的node参数递归;
                        this.sortFirst(node, i + 1);
                    }
                } else {
                    this.groupArr = [];
                    return false;
                }

            } else {
                // 若当前node的下一步节点不为group 清空下一步节点node_id 为下一次递归push id做准备
                this.list[i + 1].node_id = [];
                node.node_id.push(this.list[i + 1].id);
                this.sortFirst(this.list[i + 1], i + 1);
            }
        } else {
            return false;
        }
    }

    sortLast(node, i) {

    }

    // 在特定的开始分组节点添加组节点
    insertList(node, i) {
        if ((i + 1) === this.list.length || this.list[i + 1].type !== 'group') {
            this.list.splice(i + 1, 0, node);
            return false;
        } else {
            this.insertList(node, i + 1);
        }
    }


    // 分组和编辑节点区分
    addG = false;
    curIndex;
    // 初始化分组
    addGroup(id, index) {
        this.currNode = null;
        this.curIndex = index;
        this.addG = true;
        this.insertFlag = true
        this.modalVisible = true
        this.insertModel = new Node();
        this.insertModel.group_id = '-1'
        this.insertModel.id = this.getId();
        this.insertModel.type = 'group'
        this.insertModel.props = new Props();
    }

    addGrouping() {
        const grouping = {
            'group_id': '-1',
            'id': parseInt(this.getId()) + 1 + '',
            'node_id': [],
            'nodes': [],
            'props': {},
            'style': {},
            'text': '分组',
            'type': 'grouping',
            'visibleGroup': ['-1']
        };
        this.list.push(grouping as Node);
        this.getData();
    }



    p_data;
    come_list;

    gotoScenceEditor() {
        this.getData();
        let tempnids = new Array();
        for (let nid of this.nids) {
            for (let nodeid of this.currNode.node_id) {
                if (nodeid == nid.value) {
                    tempnids.push(nid);
                }
            }
        }
        let data = {
            n_id: this.currNode.id,
            g_id: this.currNode.group_id,
            n_name: this.currNode.text,
            n_type: this.currNode.type || '',
            g_name: this.currNode.props.group_text,
            node_id: this.currNode.node_id,
            nids: tempnids,
            p_id: this.p_id,
            p_data: this.p_data,
            gids: this.gids,
            p_width: this.p_width,
            p_height: this.p_height,
            come_list: this.currNode.visibleGroup,
            process_type: this.process_type,
            typename: this.typename
        }

        if (this.currNode.type == 'empty') {
            data.come_list = []
        }
        this.router.navigate(['xiangmu/full/scene/edit'],
            {
                queryParams: {
                    data: JSON.stringify(data) + ""
                },
                skipLocationChange: true
            })
    }

    validateForm: FormGroup;
    nids = [];
    files: any[] = [];

    ngAfterViewInit() {

    }

    refreshEnd() {

        const endNode = this.list.filter((v) => {
            return v.type === 'end';
        })[0];

        if (endNode.type === 'end') {
            for (let i = 0; i < this.list.length; i++) {
                if (this.list[i].type === 'group') {
                    if (this.list[i].nodes.length > 0) {
                        this.list[i].nodes[this.list[i].nodes.length - 1].node_id = [endNode.id];
                    }
                }
            }
        }
    }


    file

    savePdf() {
        const formData: FormData = new FormData();
        formData.append('uploadFile', this.file);
        formData.append('Type', 'Image');
        this.httpClient.post(this.Http.BASE_URL + '/fileUp/uploadFile', formData).subscribe(res => {
            if (res['code'] === '0') {
                // swal(`${res['msg']}`, '', 'info');
                this.rightSrc = this.sanitizer.bypassSecurityTrustResourceUrl(this.Http.IP_PORT + res['filepath']);
                if (this.currNode) {
                    this.currNode.props.group_img = res['filepath']
                }
                if (this.insertModel) {
                    this.insertModel.props.group_img = res['filepath']
                }
            }
        });
    }

    updateGids() {
        this.gids = new Array()
        this.gids.push({ label: '默认分组', value: '-1' });
        for (let s of this.list) {
            if (s.type == 'group') {
                this.gids.push({ label: s.props.group_text, value: s.id })
            }

        }
    }

    updateNodes() {
        this.nids = new Array()
        for (let d of this.list[this.groupIndex].nodes) {
            if (d.type == 'group') {
                for (let s of d.nodes) {
                    this.nids.push({ value: s.id, label: s.text });
                }
            } else {
                this.nids.push({ value: d.id, label: d.text });
            }

            // nzShowSearch
        }
    }

    constructor(private modal: NzModalService,public sanitizer: DomSanitizer, private Http: HttpService, public msg: NzMessageService, public httpClient: HttpClient, private http: _HttpClient, private fb: FormBuilder, public router: Router, public route: ActivatedRoute) {
    }

    getData() {

        // 更新结束节点
        // this.refreshEnd();

        this.sortFirst(this.list[0], 0);
        let p;
        // if (this.role == 3) {
        p = { p_id: this.p_id, processs: this.list, isCloud: this.typename };
        // } else {
        //     p = { p_id: this.p_id, processs: this.list, isCloud: 'false' };
        // }

        this.Http.saveFlow(p).subscribe(v => {
            if (v['code'] === '0') {
                // swal(`${v['msg']}`, '', 'info');
            }
        });
    }

    p_id;
    p_width;
    p_height;
    process_type;
    typename = '';

    ngOnInit() {


        this.groupIndex = localStorage.getItem('group-index');

        this.route.queryParams.subscribe(res => {
            this.p_id = res['p_id'];
            this.p_width = res['p_width'];
            this.p_height = res['p_height'];
            this.process_type = res['process_type'];
            this.typename = res['type_name'];
            let p;
            // if (this.role == 3) {
            p = { p_id: this.p_id, isCloud: res['type_name'] };
            // } else {
            //     p = { p_id: this.p_id, isCloud: 'false' }
            // }
            console.log(res['type_name'])
            this.Http.getProjProcess(p).subscribe(res => {
                // this.list=res;
                // this.list = JSON.parse(res['list'][0]['p_data'])
                console.log(res)
                if (res['list'].length === 0) {
                    this.addBeginAndGroup();
                } else {
                    this.list = JSON.parse(res['list'][0]['p_data']);
                }

                this.updateGids();
                this.updateNodes();
            })
        });

        this.validateForm = this.fb.group({
            s1: [null, [Validators.email]],
            s2: [null, [Validators.email]],
            s3: [null, [Validators.email]],
            s4: [null, [Validators.email]],
            s5: [null, [Validators.email]],
            s6: [null, [Validators.email]],
            s7: [null, [Validators.email]],
            s46: [null, [Validators.email]],
            s67: [null, [Validators.email]],
            s678: [null, [Validators.email]]

        });
    }

    getId() {
        return new Date().getTime() + "";
    }


    add() {
        this.modalVisible = true;
        this.description = '';
    }

    save() {
        //console.log(this.currNode)
        if (this.currNode) {
            //console.log('修改')
            if (this.currNode.type == 'start') {
                if (this.currNode.text == '') {
                    swal('节点名称不能为空', '', 'info');
                    return
                }
            }
            if (this.currNode.type == 'grouping') {
                if (this.currNode.text == '') {
                    swal('节点名称不能为空', '', 'info');
                    return
                }
            }
            if (this.currNode.type == 'group') {
                if (new RegExp(/^\s*$/).test(this.currNode.props.group_text)) {
                    swal('分组名称不能为空', '', 'info');
                    return
                }
                if (this.currNode.props.group_img == '') {
                    swal('分组图标不能为空', '', 'info');
                    return
                }
                if (this.currNode.props.group_type == '') {
                    swal('分组类型不能为空', '', 'info');
                    return
                }
                if (this.currNode.props.group_limit == '') {
                    swal('分组人数不能为空', '', 'info');
                    return
                }
            }
            if (this.currNode.type == 'process') {
                if (this.currNode.text == "") {
                    swal('节点名称不能为空', '', 'info');
                    return
                }
                if (this.currNode.type == "") {
                    swal('节点类型不能为空', '', 'info');
                    return
                }
                if (!this.currNode.visibleGroup.length) {
                    swal('可见组不能为空', '', 'info');
                    return
                }
            }
        } else {
            // console.log('新增');
            // console.log(this.insertModel)
            if (this.insertModel.type == 'group') {
                if (new RegExp(/^\s*$/).test(this.insertModel.props.group_text)) {
                    swal('分组名称不能为空', '', 'info');
                    return
                }
                if (!this.insertModel.props.group_img) {
                    swal('分组图标不能为空', '', 'info');
                    return
                }
                if (!this.insertModel.props.group_type) {
                    swal('分组类型不能为空', '', 'info');
                    return
                }
                if (!this.insertModel.props.group_limit) {
                    swal('分组人数不能为空', '', 'info');
                    return
                }
            }
        }
        this.loading = true;
        setTimeout(() => {
            this.modalVisible = false
            this.loading = false;
            this.rightSrc = '';
            this.addG = false;
        }, 500);


        if (this.addG) {
            this.insert();
        } else {
            saveRule(this.description);
            this.getData();
        }
    }

    close() {
        this.rightSrc = '';
        this.modalVisible = false;
        this.addG = false;
        this.ngOnInit()
    }

    remove() {
        this.selectedRows.forEach(i => removeRule(i.no));
        this.getData();
        this.clear();
    }

    approval() {
        this.msg.success(`审批了 ${this.selectedRows.length} 笔`);
    }

    clear() {
        this.selectedRows = [];
        this.totalCallNo = 0;
        this.data.forEach(i => i.checked = false);
        this.refreshStatus();
    }

    checkAll(value: boolean) {
        this.curRows.forEach(i => {
            if (!i.disabled) i.checked = value;
        });
        this.refreshStatus();
    }

    refreshStatus() {
        const allChecked = this.curRows.every(value => value.disabled || value.checked);
        const allUnChecked = this.curRows.every(value => value.disabled || !value.checked);
        this.allChecked = allChecked;
        this.indeterminate = (!allChecked) && (!allUnChecked);
        this.selectedRows = this.data.filter(value => value.checked);
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total + cv.callNo, 0);
    }

    getIndexInGroup(groupid) {
        let arr;
        for (let g of this.list) {
            if (g.id == groupid) {
                arr = g.nodes
            }
        }
        return arr.indexOf(this.currNode)
    }

    left(groupid) {
        let i = this.getIndexInGroup(groupid)
        if (i == 0) {
            return
        }
        this.swapItem(groupid, i, i - 1);

    }

    right(groupid) {
        let i = this.getIndexInGroup(groupid)
        let arr;
        for (let g of this.list) {
            if (g.id == groupid) {
                arr = g.nodes
            }
        }

        if (i == arr.length - 1) {
            return
        }
        this.swapItem(groupid, i, i + 1);
    }

    swapItem(groupid, i, j) {
        let arr;
        for (let g of this.list) {
            if (g.id == groupid) {
                arr = g.nodes
            }
        }
        if (arr) {
            arr[i] = arr.splice(j, 1, arr[i])[0]
            return arr
        }
    }

    sortNextId(g_id) {
        const obj = this.list.filter((v, i) => {
            if (g_id === v.id) {
                return true;
            }
        })[0];

        // console.log(obj)

        if (obj.nodes.length > 1) {
            for (let i = 0; i < obj.nodes.length - 1; i++) {
                obj.nodes[i].node_id = [obj.nodes[i + 1].id];
            }
        }
    }
    groupIndex = '0';
    switchGroup(l, i) {
        this.groupIndex = i;
        localStorage.setItem('group-index', i);
    }
    deleteModel(n,id) {
        this.modal.open({
            title: '删除提示',
            content: '是否删除该节点？',
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                this.deleteNodeSelf(n, id)
            },
            onCancel: () => {

            }
        });
    }
    deleteNodeSelf(n, id) {

        //console.log(id);

        this.modalVisible = false;

        for (let d of this.list) {
            if (d.id == n.id) {
                let index = this.list.indexOf(d, 0);
                if (index > -1) {
                    this.list.splice(index, 1);
                }
            }

            if (d.type == 'group') {
                for (let s of d.nodes) {
                    if (s.id == n.id) {
                        let index = d.nodes.indexOf(s);
                        if (index > -1) {
                            d.nodes.splice(index, 1);
                        }
                    }
                }
            }

        }

        this.filterNodeId();
        this.sortNextId(id);
        this.updateGids();
        this.updateNodes();
        this.getData();
    }

    deleteNode() {
        this.modalVisible = false;

        for (let d of this.list) {
            if (d.id == this.currNode.id) {
                let index = this.list.indexOf(d, 0);
                if (index > -1) {
                    this.list.splice(index, 1);
                }
            }

            if (d.type == 'group') {
                for (let s of d.nodes) {
                    if (s.id == this.currNode.id) {
                        let index = d.nodes.indexOf(s);
                        if (index > -1) {
                            d.nodes.splice(index, 1);
                        }
                    }
                }
            }

        }

        this.filterNodeId();
        this.getData()
        this.updateGids();
        this.updateNodes();
    }

    preview() {
        this.router.navigate(['../../advance'], { relativeTo: this.route, queryParams: { p_id: this.p_id, isCloud: this.typename, isUse: true } });
    }

    sort(field: string, value: any) {
        this.sortMap = {};
        this.sortMap[field] = value;
        this.q.sorter = value ? `${field}_${value}` : '';
        this.getData();
    }

    dataChange(res: any) {
        this.curRows = res;
        this.refreshStatus();
    }

    pageChange(pi: number): Promise<any> {
        this.q.pi = pi;
        this.loading = true;
        return new Promise((resolve) => {
            setTimeout(() => {
                this.loading = false;
                resolve();
            }, 500);
        });
    }

    reset(ls: any[]) {
        for (const item of ls) item.value = false;
        this.getData();
    }

    //
    sortArr(arr: Array<any>) {
        let temp;
        for (let i = 0; i < arr.length; i++) {
            for (let j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j].finalAnswer.length < arr[j + 1].finalAnswer.length) {
                    temp = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        const finalArr = this.sortArrFinal(arr, 0, []);
    }
    sortArrFinal(arr, i, pushArr: any) {
        if (i === arr.length - 1) {
            if (arr[i].finalAnswer.length === arr[i - 1].finalAnswer.length) {
                return pushArr;
            } else {
                pushArr.push([arr[i].groupId]);
                return pushArr;
            }
        }
        const temp = [arr[i].groupId];
        let index;
        for (let j = i + 1; j < arr.length; j++) {
            index = j;
            if (arr[i].finalAnswer.length === arr[j].finalAnswer.length) {
                temp.push(arr[j].groupId);
            } else {
                break;
            }
        }
        this.sortArrFinal(arr, index, pushArr.push(temp));
    }

}



export class Node {
    public id;
    public type;
    public text;
    public group_id;
    public visibleGroup = new Array;
    public node_id = new Array<string>();
    public nodes = new Array<Node>();
    public style = new Style();
    public props = new Props();
}

export class Style {

}

export class Props {
    public group_text;
    public group_img = '';
    public group_type;
    public group_limit;
}
